package com.mask.im.server.netty.action.handler;

import com.alibaba.fastjson.JSON;
import com.mask.im.server.netty.IMChannelCtxMap;
import com.mask.im.server.netty.enums.IMActionEnum;
import com.mask.im.server.netty.model.IMReceiveMessage;
import com.mask.im.server.netty.model.IMSendMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @className： IMTypingActionHandler
 * @Description: 正在输入中状态操作
 * @Author：jian
 * @Date：2025/10/13 16:28
 */
@Log4j2
@Component
public class IMTypingActionHandler extends IMAbstractChatHandler {
    @Override
    public IMActionEnum getAction() {
        return IMActionEnum.TYPING;
    }

    @Override
    public void handle(IMReceiveMessage imReceiveMessage, Channel channel) {
        AttributeKey<Long> userIdAttributeKey = AttributeKey.valueOf("USER_ID");
        Long userId = channel.attr(userIdAttributeKey).get();
        log.info("netty发送输入中状态 id:{}", userId);
        // 绑定用户数据
        Long receiverId = imReceiveMessage.getReceiverId();
        if (null != receiverId) {
            Channel receiverChannel = IMChannelCtxMap.getUserIdChannel(receiverId.toString());
            if (Objects.nonNull(receiverChannel)) {
                // 响应ws
                IMSendMessage sendInfo = new IMSendMessage();
                sendInfo.setCmd(IMActionEnum.TYPING.getAction());
                receiverChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(sendInfo)));
            }
        }
    }
}
